package com.company.common.core.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {

	public static <T> T fromJson(Class<T> tclass, String json) {
		if (StringUtils.isEmpty(json) == false) {
			Gson gson = new Gson();
			return (T) gson.fromJson(json, tclass);
		}
		return null;
	}
	
	public static <T> T fromJson(Type t,String json){
		
		if (StringUtils.isEmpty(json) == false) {
			Gson gson = new Gson();
			return gson.fromJson(json,t);
		}
		return null;
	}
	
	public static <T> String toJson(T t){
		Gson gson = new Gson();
		return gson.toJson(t);
	}
	
	
	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
		
		Map<String,List<A>> tmp =new HashMap<String,List<A>>();
		
		List<A> t = new ArrayList<A>();
		t.add(new A("a"));
		t.add(new A("b"));
		
		tmp.put("tt", t);
		
		String json = toJson(tmp);
		System.out.println(json);
		
		
		ObjectMapper mapper = new ObjectMapper();
		mapper.enableDefaultTyping();
		
		Map<String,List<A>> tt = mapper.readValue(json, new TypeReference<Map<String,List<A>>>() {});
		
		System.out.println(tt.size());
	}
	
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> Json2Map(String str) {

		Map<String, Object> map = new HashMap<String, Object>();

		ObjectMapper mapper = new ObjectMapper();
		//String s = "{ \"name\" : \"萧远山\", \"sex\" : \"男\", \"age\" : \"23\",\"address\" : \"河南郑州\"}";
		try {
			map = mapper.readValue(str, Map.class);

			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return map;
	}

	public static String Map2Json(Map<String,Object> map){
		String s = "";

		ObjectMapper mapper = new ObjectMapper();
		try {
			s = mapper.writeValueAsString(map);
		} catch (Exception e) {
			// TODO: handle exception
		}

		return s;
	}

}
